import 'dart:ui';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:yinshui_caiying/http/api_alarm.dart';
import 'package:yinshui_caiying/http/http.dart';
import 'package:yinshui_caiying/model/alarm_result_model.dart';
import 'package:yinshui_caiying/services/common_services.dart';
import 'package:yinshui_caiying/utils/colors.dart';
import 'package:yinshui_caiying/widgets/appbar.dart';
import "package:flutter_screenutil/flutter_screenutil.dart";
import 'package:yinshui_caiying/widgets/action_text_button.dart';
import 'package:yinshui_caiying/widgets/loading.dart';
import 'package:yinshui_caiying/widgets/noData.dart';
import 'package:yinshui_caiying/widgets/picker/pickers.dart';

class AlarmListPage extends StatelessWidget {
  AlarmListPageController vm = Get.put(AlarmListPageController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BackTitleBar(
          title: '报警列表',
          action: Row(
            children: [
              // ActionTextButton(
              //     title: '近七天',
              //     width: 70.w,
              //     height: 34.h,
              //     onPressed: () {
              //       Get.toNamed('/collection');
              //     }),
            ],
          )),
      body: SafeArea(
          child: Container(
              decoration:
                  BoxDecoration(color: Color.fromRGBO(240, 242, 245, 1)),
              child: Column(
                children: [menuBar(context), Obx(() => listBar(context))],
              ))),
    );
  }

  Widget menuBar(BuildContext context) {
    return Container(
      width: 1.sw,
      height: 140.h,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
            bottom: BorderSide(
                width: 2.h, color: Color.fromRGBO(229, 229, 229, 1))),
      ),
      child: Row(
        children: [
          // menuItem(context, '行政区划', vm.ad_name, vm.treePicker),

          Expanded(
              child: TextButton(
                  onPressed: () async {
                    var result = await showDatePicker(
                        context: Get.context!,
                        initialDate: vm._time.value != ''
                            ? DateTime.parse(vm._time.value)
                            : DateTime.now(),
                        lastDate: DateTime.now(),
                        firstDate: DateTime(2019));

                    if (result != null) {
                      vm._time.value = DateUtil.formatDate(result,
                          format: DateFormats.y_mo_d);
                      vm._searchByTime();
                    } else {
                      vm._time.value = '';
                      vm._searchByTime();
                    }
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Obx(() => Text(
                            vm._time.value == '' ? '选择时间' : vm._time.value,
                            style: TextStyle(color: Colors.black),
                          )),
                      Container(
                        margin: EdgeInsets.only(left: 24.w),
                        child: Icon(
                          Icons.expand_more,
                          color: Color.fromRGBO(204, 204, 204, 1),
                          size: 30.w,
                        ),
                      ),
                    ],
                  ))),
          Container(
            width: 1.w,
            color: Color.fromRGBO(204, 204, 204, 1),
          ),
          Expanded(
            child: TextButton(
                onPressed: () {
                  Pickers.showAdPicker(
                      selectData: vm._adId,
                      data: vm.commonService.adList,
                      onConfirm: (value) {
                        vm._searchProjectAdId(value);
                      },
                      onAll: (value) {
                        vm._searchProjectAdId(value);
                      });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Obx(() => Text(
                          vm._adName.value,
                          style: TextStyle(color: Colors.black),
                        )),
                    Container(
                      margin: EdgeInsets.only(left: 24.w),
                      child: Icon(
                        Icons.expand_more,
                        color: Color.fromRGBO(204, 204, 204, 1),
                        size: 30.w,
                      ),
                    ),
                  ],
                )),
          )
        ],
      ),
    );
  }

  Widget menuItem(
    BuildContext context,
    String title,
    Rx<String> name,
    dynamic Function(BuildContext, String) onPressed,
  ) {
    return Expanded(
      child: TextButton(
          onPressed: onPressed(context, title),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Obx(() => Text(
                    title + (name.value != '' ? '(' + name.value + ')' : ''),
                    overflow: TextOverflow.fade,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 42.sp,
                      fontWeight: FontWeight.w400,
                      fontFamily: "PingFang SC",
                    ),
                  )),
              Container(
                margin: EdgeInsets.only(left: 24.w),
                child: Icon(
                  Icons.expand_more,
                  color: Color.fromRGBO(204, 204, 204, 1),
                  size: 42.w,
                ),
              ),
            ],
          )),
    );
  }

  ///列表状态
  ///
  ///[index]为项目的索引
  Widget _showMore(index) {
    if (vm._hasMore.value) {
      if (index == vm._alarmList.length - 1) {
        return LoadingWidget();
      } else {
        return Text('');
      }
    } else {
      return (index == vm._alarmList.length - 1)
          ? Text('我是有底线的',
              style: TextStyle(
                color: Color.fromRGBO(119, 119, 119, 0.6),
                fontSize: 34.sp,
              ))
          : Text('');
    }
  }

  Widget listBar(BuildContext context) {
    return Expanded(
        child: RefreshIndicator(
      onRefresh: vm._onRefresh,
      child: vm._alarmList.length > 0
          ? ListView.builder(
              controller: vm._scrollController,
              itemCount: vm._alarmList.length,
              physics: AlwaysScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                return Column(children: [
                  listItem(index),
                  SizedBox(
                    height: 20.h,
                  ),
                  _showMore(index)
                ]);
              },
            )
          : vm._flag
              ? NoDataWidget()
              : LoadingWidget(),
    ));
  }

  Widget listItem(int index) {
    AlarmItemModel item = vm._alarmList[index];
    return Container(
        width: 1.sw,
        decoration: BoxDecoration(color: Colors.white),
        margin: EdgeInsets.only(top: 31.h),
        padding: EdgeInsets.fromLTRB(103.w, 50.h, 59.w, 51.h),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                    child: Text(
                  "${item.alarmAddress}-${item.userName}",
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  textAlign: TextAlign.start,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 38.sp,
                    fontWeight: FontWeight.w500,
                    fontFamily: "PingFang SC",
                  ),
                )),
                Container(
                  width: 63.w,
                  height: 63.w,
                  child: InkWell(
                    onTap: () {
                      print("导航到");
                      vm._linkToMap(index);
                    },
                    child: Image.asset('assets/images/list/icon-to-map.png'),
                  ),
                )
              ],
            ),
            Container(
              margin: EdgeInsets.only(top: 38.h),
              height: 200.h,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      listItemText("报警时间:${item.alarmTime}"),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          listItemText("报警事件："),
                          Text(
                            "${item.alarmEvent}",
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                            style: TextStyle(
                              color: Colors.red,
                              fontSize: 32.sp,
                              fontWeight: FontWeight.w400,
                              fontFamily: "PingFang SC",
                            ),
                          ),
                        ],
                      )
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      listItemText("基表号:${item.tableNum}"),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          listItemText("阀门状态："),
                          Text(
                            "${item.isOpen != null && item.isOpen == '1' ? '开启' : '关闭'}",
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                            style: TextStyle(
                              color: item.isOpen != null && item.isOpen == '1'
                                  ? MyColors.main
                                  : Colors.red,
                              fontSize: 32.sp,
                              fontWeight: FontWeight.w400,
                              fontFamily: "PingFang SC",
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      listItemText("所属表井：${item.projectName}"),
                    ],
                  ),
                ],
              ),
            )
          ],
        ));
  }

  Widget listItemText(String name) {
    return Text(name,
        overflow: TextOverflow.ellipsis,
        maxLines: 1,
        style: TextStyle(
          color: Color.fromRGBO(96, 96, 96, 1),
          fontSize: 32.sp,
          fontWeight: FontWeight.w400,
          fontFamily: "PingFang SC",
        ));
  }
}

class AlarmListPageController extends GetxController {
  CommonService commonService = Get.find();

  ///下滑判断开关
  bool _flag = true;

  ///页码
  int _page = 1;

  ///一页多少个
  int _pageSize = 10;

  ///是否有更多
  final _hasMore = true.obs;

  ///是否有数据
  final _hasData = true.obs;

  ///行政区划名称
  final _adName = '行政区划'.obs;

  ///行政区划id
  int? _adId = 0;

  ///模糊查询
  String _keywords = '';

  ///日期查询
  final _time = ''.obs;

  ///工程id
  int _projectId = 0;

  ///按日期查询
  _searchByTime() async {
    _resetParams();

    _getProjectListData();
  }

  ///ListView滑动控制器
  ScrollController _scrollController = ScrollController();
  final _alarmList = <AlarmItemModel>[].obs;

  ///模糊查询的控制器
  TextEditingController _keywordsController = TextEditingController();
  @override
  void onInit() async {
    if (Get.arguments != null) {
      _keywords = Get.arguments.params;
      _keywordsController.text = Get.arguments.params;
      _adId = Get.arguments.ad_id != null ? Get.arguments.ad_id : 0;
      _adName.value =
          Get.arguments.ad_name != null ? Get.arguments.ad_name : '行政区划';
    }

    // _projectType(commonService.projectTypeList[0]);
    final availableMaps = await MapLauncher.installedMaps;
    availableMaps.forEach((element) {
      print(element.mapName);
    });
    print(availableMaps);

    ///初始化时先拿一次数据
    _getProjectListData();

    ///监听ListView滚动事件

    _scrollController.addListener(() {
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 20) {
        if (_flag && _hasMore.value) {
          _getProjectListData();
        }
      } else {}
    });
    super.onInit();
  }

  ///按行政区划查询
  _searchProjectAdId(dynamic data) async {
    _resetParams();

    if (data == null) {
      _adName.value = '全部';
      _adId = 0;
    } else {
      _adName.value = data[data.length - 1].name;
      _adId = data[data.length - 1].id;
    }

    ///重新请求数据
    await _getProjectListData();
  }

  ///重置查询数据
  _resetParams() {
    //重置分页数
    _page = 1;

    //重置数据
    _alarmList.clear();

    //滚动条回到顶部
    if (_alarmList.length > 0) {
      _scrollController.jumpTo(0);
    }

    //重置hasmore
    _hasMore.value = true;
  }

  ///下拉刷新
  Future<void> _onRefresh() async {
    _resetParams();

    //重新请求数据
    await _getProjectListData();
  }

  ///打开导航
  _linkToMap(index) async {
    AlarmItemModel item = _alarmList[index];

    Coords coords = Coords(item.latitude, item.longitude);
    String title = item.projectName;
    int zoom = 16;
    var hasgaode = await MapLauncher.isMapAvailable(MapType.amap);
    var hasbaidu = await MapLauncher.isMapAvailable(MapType.baidu);
    if (hasgaode != null && hasgaode) {
      ///如果有高德优先打开高德
      await MapLauncher.showMarker(
        mapType: MapType.amap,
        coords: coords,
        title: title,
        zoom: zoom,
        description: '工程位置',
      );
    } else if (hasbaidu != null && hasbaidu) {
      ///如果没有高德则去找百度
      await MapLauncher.showMarker(
        mapType: MapType.baidu,
        coords: coords,
        title: title,
        zoom: zoom,
        description: '工程位置',
      );
    } else {
      ///都没有则提示未安装app
      SmartDialog.showToast('手机未安装任何地图应用');
    }
  }

  ///获取报警列表
  Future<void> _getProjectListData() async {
    _flag = false;

    try {
      var res = await Http().post(
        ApiAlarm.ALARM_LIST,
        data: {
          'params': {
            "ad_id": _adId,
            "sch_date": _time.value,
            'project_id': _projectId
          },
          'paginate': {"total": 0, "page": _page, 'per_page': _pageSize},
        },
      );
      AlarmListResultModel result = AlarmListResultModel.fromJson(res);
      if (result.code == 200) {
        _alarmList.addAll(result.content.data);
        _page++;
        _flag = true;
        if (result.content.data.length < _pageSize) {
          _hasMore.value = false;
        }
        if (_alarmList.length == 0) {
          _hasData.value = false;
        } else {
          _hasData.value = true;
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }
}
